export class Request {
  constructor(io, opt) {
    this.io = io
    this._debug = false
    this.opt = {
      base: '',
      ...opt,
    }
  }

  handleServerErr(e) {}

  getRequestArgs(...args) {
    let fullPath = ''
    if (args.length < 2) {
      if (typeof args[0] === 'object' && args[0].hasOwnProperty('path')) {
        fullPath = this.opt.base + args[0].path
        return [
          fullPath,
          {
            ...args[0].params,
          },
        ]
      }
      fullPath = this.opt.base + args[0]
      return [
        fullPath,
        {},
      ]
    } else {
      if (typeof args[0] === 'string') {
        fullPath = this.opt.base + args[0]
        return [
          fullPath,
        ].concat(args.slice(1))
      }
      return args
    }
  }

  async get(...args) {
    let requestArgs = this.getRequestArgs(...args)
    if (this._debug) {
      console.log('requestArgs :', requestArgs)
    }
    try {
      let res = await this.io.get(...requestArgs)
      return res
    } catch (e) {
      console.error(e)
      if (this.handleServerErr) {
        this.handleServerErr(e)
      }
    }
  }

  async post(...args) {
    let requestArgs = this.getRequestArgs(...args)
    try {
      let res = await this.io.post(...requestArgs)
      return res
    } catch (e) {
      console.error(e)
      if (this.handleServerErr) {
        this.handleServerErr(e)
      }
    }
  }

  async put(...args) {
    let requestArgs = this.getRequestArgs(...args)
    try {
      let res = await this.io.put(...requestArgs)
      return res
    } catch (e) {
      console.error(e)
      if (this.handleServerErr) {
        this.handleServerErr(e)
      }
    }
  }

  async delete(...args) {
    let requestArgs = this.getRequestArgs(...args)
    try {
      let res = await this.io.delete(...requestArgs)
      return res
    } catch (e) {
      console.error(e)
      if (this.handleServerErr) {
        this.handleServerErr(e)
      }
    }
  }
}
